import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../shared/services/auth_service.dart';
import '../core/utils/logger.dart';

// 简化的认证中间件
class AuthMiddleware extends GetMiddleware {
  @override
  int? get priority => 1;

  @override
  RouteSettings? redirect(String? route) {
    if (route == null) return null;
    
    final authService = AuthService.instance;
    
    // 检查是否已认证
    if (!authService.isAuthenticated) {
      AppLogger.info('User not authenticated, redirecting to login');
      return const RouteSettings(name: '/login');
    }
    
    return null;
  }
}

// 简化的访客中间件
class GuestMiddleware extends GetMiddleware {
  @override
  int? get priority => 1;

  @override
  RouteSettings? redirect(String? route) {
    if (route == null) return null;
    
    final authService = AuthService.instance;
    
    // 如果用户已登录，重定向到首页
    if (authService.isAuthenticated) {
      AppLogger.info('User already authenticated, redirecting to home');
      return const RouteSettings(name: '/home');
    }
    
    return null;
  }
}

// 简化的日志中间件
class LoggingMiddleware extends GetMiddleware {
  @override
  int? get priority => 0;

  @override
  GetPage? onPageCalled(GetPage? page) {
    if (page != null) {
      AppLogger.page(page.name, params: Get.parameters);
    }
    return super.onPageCalled(page);
  }
}

// 错误页面组件
class ErrorPage extends StatelessWidget {
  final String error;
  
  const ErrorPage({Key? key, required this.error}) : super(key: key);
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('发生错误')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.error, size: 64, color: Colors.red),
            const SizedBox(height: 16),
            const Text('发生错误', style: TextStyle(fontSize: 18)),
            const SizedBox(height: 8),
            Text(error, style: const TextStyle(color: Colors.grey)),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: () => Get.back(),
              child: const Text('返回'),
            ),
          ],
        ),
      ),
    );
  }
}

// 未授权页面组件
class UnauthorizedPage extends StatelessWidget {
  const UnauthorizedPage({Key? key}) : super(key: key);
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('权限不足')),
      body: const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.lock, size: 64, color: Colors.orange),
            SizedBox(height: 16),
            Text('权限不足', style: TextStyle(fontSize: 18)),
            SizedBox(height: 8),
            Text('您没有权限访问此页面', style: TextStyle(color: Colors.grey)),
          ],
        ),
      ),
    );
  }
}